﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;

namespace ProjektXNA
{
    class Player
    {
        public int lives { get; set; }
        public int money { get; set; }
        //public int income { get; set; }

        private List<Tower> towers = new List<Tower>();

        private MouseState mouseState;
        private MouseState oldState;

        private Level level;
        private Texture2D towerTexture;

        private int cellX;
        private int cellY;

        private int tileX;
        private int tileY;

        public Player(Level level, Texture2D towerTexture)
        {
            this.level = level;
            this.towerTexture = towerTexture;
        }

        public void Update(GameTime gameTime, List<Enemy> enemies)
        {
            mouseState = Mouse.GetState();

            cellX = (int)(mouseState.X / 32);
            cellY = (int)(mouseState.Y / 32);

            tileX = cellX * 64;
            tileY = cellY * 64;

            if (oldState.LeftButton == ButtonState.Pressed
                && mouseState.LeftButton == ButtonState.Released)
            {
                if (emptyCell())
                {
                    Tower tower = new Tower(towerTexture, new Vector2(tileX, tileY));
                    towers.Add(tower);
                }
            }

            foreach (Tower tower in towers)
            {
                if (tower.target == null)
                    tower.nearestEnemy(enemies);

                tower.Update(gameTime);
            }

            oldState = mouseState;
        }

        public bool emptyCell()
        {
            bool inLimit = cellX >= 0 && cellY >= 0 && cellX < level.Data.GetLength(1) && cellY < level.Data.GetLength(0);

            bool cellClear = true;

            foreach (Tower tower in towers)
            {
                cellClear = (tower.Position != new Vector2(tileX, tileY));

                if (!cellClear)
                    break;
            }

            bool onPath = (level.getIndex(cellX, cellY) != 1);

            return inLimit && cellClear && onPath;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            foreach(Tower tower in towers)
            {
                tower.Draw(spriteBatch);
            }
        }

    }
}
